package com.thread.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by user on 17/8/10.
 */
public class SemaphoreTest {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // 线程池
        ExecutorService exec = Executors.newCachedThreadPool();

        // 只能3个线程同时访问
        final Semaphore semph = new Semaphore(3);
        // 模拟个客户端访问
        for (int index = 1; index < 10; index++) {
            final int NO = index;
            Runnable ru = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        semph.acquire();
                        System.out.println("accessing: " + NO);

                        Thread.sleep(2000);
                        // 访问完后，释放
                        System.out.println("release: " + NO);
                        semph.release();
                    } catch (InterruptedException e) {
                    }
                }
            };
            exec.execute(ru);
        }
        // 退出线程池
        exec.shutdown();
    }
}
